package com.fingard.dsp.web;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import com.fingard.net.niosocket.HttpNioReceiver;
import com.fingard.text.StringHelper;

public class HttpRequest {
	
	public HttpNioReceiver httpReceiver;
	
	public static final String Browser_Chrome = "chrome";
	
	public String webBrowser;
	
	public HttpRequest(HttpNioReceiver p_httpReceiver){
		httpReceiver = p_httpReceiver;
		//user-agent=mozilla/5.0 (windows nt 6.3; wow64) applewebkit/537.36 (khtml, like gecko) chrome/55.0.2883.75 safari/537.36
		if(httpReceiver.headKV.containsKey("user-agent")){
			String agentValue = httpReceiver.headKV.get("user-agent");
			if(agentValue != null && agentValue.contains(Browser_Chrome)){
				webBrowser = Browser_Chrome;
			}
		}
	}
	
	/**url里的查询字符串，?xxx=ddd，问号之后的字符串*/
	public String queryString;

	/**取查询字符串的key-value对*/
	public HashMap<String,String> getQryKeyValues() throws UnsupportedEncodingException{
		HashMap<String,String> retMap = new HashMap<String,String>();
		if(StringHelper.hasAnyChar(queryString)){
			retMap = StringHelper.splitQryStringDecode(queryString, "gbk", true, true);
		}
		return retMap;
	}
	
	/**取form提交的key-value对*/
	public HashMap<String,String> getFormKeyValues() throws UnsupportedEncodingException{
		return StringHelper.splitQryStringDecode(httpReceiver.getReqBodyContent(), "gbk", true, true);
	}
	
	/**查询字符串的map*/
	private HashMap<String,String> qryStrMap;
	
	/**获取查询字符串的map
	 * @throws UnsupportedEncodingException */
	private HashMap<String,String> getQryStrMap() throws UnsupportedEncodingException{
		if(qryStrMap == null){
			qryStrMap = getQryKeyValues();
		}
		return qryStrMap;
	}
	
	/**获取查询字符串Key对应的value
	 * @throws UnsupportedEncodingException */
	public String getQryStrValue(String pKey) throws UnsupportedEncodingException{
		if(getQryStrMap().containsKey(pKey.toLowerCase())){
			return getQryStrMap().get(pKey.toLowerCase()); 
		}
		return null;
	}
	
	public String getPage(){
		if(StringHelper.hasAnyChar(httpReceiver.visitPage)){
			String vPage = httpReceiver.visitPage;
			int idx = vPage.indexOf("?");
			if(idx>=0){
				queryString = vPage.substring(idx+1);
				return vPage.substring(0, idx);
			}else{
				return vPage;
			}
		}
		return "/";
	}
}
